package com.atguigu.tingshu.search.consumer;

import com.atguigu.tingshu.search.service.ItemService;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/***
 * 监听专辑上下架消息
 */
@Component
@Log4j2
public class AlbumAndSearchConsumer {
    @Autowired
    private ItemService itemService;

    /**
     * 上架消费者
     */
    @SneakyThrows
    @RabbitListener(queues = "album_and_search_queue_upper")
    public void albumUpperConsumer(Channel channel, Message message){
        // 获取专辑id信息
        byte[] body = message.getBody();
        Long albumId = Long.valueOf(new String(body));
        // 获取消息属性
        MessageProperties messageProperties = message.getMessageProperties();
        // 获取消息编号
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            // 上架
            itemService.addAlbumFromMysqlToEs(albumId);
            // 确认
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            e.printStackTrace();
            // 判断消息是否第一次消费失败
            if (messageProperties.getRedelivered()){
                log.error("上架消息消费失败，专辑id"+albumId+"，失败原因"+e.getMessage());
                channel.basicReject(deliveryTag,false);
            }else {
                channel.basicReject(deliveryTag,true);
            }
        }
    }

    /**
     * 下架消费者
     */
    @SneakyThrows
    @RabbitListener(queues = "album_and_search_queue_down")
    public void albumDownConsumer(Channel channel, Message message){
        // 获取专辑id信息
        byte[] body = message.getBody();
        Long albumId = Long.valueOf(new String(body));
        // 获取消息属性
        MessageProperties messageProperties = message.getMessageProperties();
        // 获取消息编号
        long deliveryTag = messageProperties.getDeliveryTag();
        try {
            // 上架
            itemService.removeFromEs(albumId);
            // 确认
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            e.printStackTrace();
            // 判断消息是否第一次消费失败
            if (messageProperties.getRedelivered()){
                log.error("下架消息消费失败，专辑id"+albumId+"，失败原因"+e.getMessage());
                channel.basicReject(deliveryTag,false);
            }else {
                channel.basicReject(deliveryTag,true);
            }
        }
    }


}
